﻿using System;
using System.Linq;
using System.Reflection;

namespace Se.Framework.Common.Extentions
{
    public static class TypeExtentions
    {
        public static T Attribute<T>(this Type type)
            where T : Attribute
        {
            return type.GetCustomAttributes(typeof(T), true).OfType<T>().FirstOrDefault();
        }

        public static T Attribute<T>(this PropertyInfo property)
            where T : Attribute
        {
            return property.GetCustomAttributes(typeof(T), true).OfType<T>().FirstOrDefault();
        }

        public static bool TrySetValueFromString(this PropertyInfo property, string str, object objectToSet)
        {
            var type = property.PropertyType;
            if (type == typeof(string))
            {
                property.SetValue(objectToSet, str, null);
            }

            if (!type.IsValueType || type.Namespace != "System")
            {
                return false;
            }
            if (!string.IsNullOrWhiteSpace(str))
            {
                var method = type.GetMethod("Parse", new[] { typeof(string) });
                if (method == null)
                {
                    var underlyingType = Nullable.GetUnderlyingType(type);
                    if (underlyingType != null)
                    {
                        method = underlyingType.GetMethod("Parse", new[] { typeof(string) });
                    }
                }
                if (method != null)
                {
                    property.SetValue(objectToSet, method.Invoke(null, new object[] { str }), null);
                    return true;
                }
            }
            return false;
        }
    }
}